package com.wechat.service.account.starter;

import com.alibaba.fastjson.JSONObject;
import com.wechat.service.account.config.WechatServiceAccountConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author yanggld
 * @Date 2019/7/10-15:47
 * @Description
 * 服务号access_token相关
 */
@Slf4j
@Service
public class AccessTokenService {

	@Autowired
	private WechatServiceAccountConfig accountConfig;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 请求得到access_token，返回null表示获取失败
	 * @return
	 */
	public String reqAccessToken(){
		ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(buildAccessTokenUrl(), JSONObject.class);
		JSONObject body = responseEntity.getBody();
		log.info("*******获取access_token的结果：{}********",JSONObject.toJSONString(body));
		String accessToken = body.getString("access_token");
		return accessToken;
	}

	public String buildAccessTokenUrl(){
		return  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+accountConfig.getAppId()+"&secret="+accountConfig.getAppSecret();
	}

	/**
	 * 获取access_token
	 * @return
	 */
	public String getAccessToken(){
		String accessToken = getAccessTokenFromCache();
		if (StringUtils.isEmpty(accessToken)) {
			return getAccessTokenFromWechat();
		}
		return accessToken;
	}

	private String accessTokenKey = "wechat:service:account:access_token";

	/**
	 * 调用微信接口请求access_token并缓存时间为118分钟
	 * @return
	 */
	public String getAccessTokenFromWechat(){
		String accessToken = reqAccessToken();
		if (!StringUtils.isEmpty(accessToken)) {
			stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,118L, TimeUnit.MINUTES);
			return accessToken;
		}
		return null;
	}

	/**
	 * 从缓存中获取access_token
	 * @return
	 */
	public String getAccessTokenFromCache(){
		return stringRedisTemplate.opsForValue().get("wechat:service:account:access_token");
	}

}
